import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { downloadByUrl, deviceDetection,getKeyList } from "@pureadmin/utils";

import {getExpressFeeList, importCaseList, importExpressFeeList,} from "@/api/system";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { utils, writeFile, readFile } from "xlsx";
import {addDrawer} from "@/components/ReDrawer/index";
// import forms, {FormProps} from "@/views/components/drawer/form.vue";
import forms, { type FormProps } from "../import.vue";


export function useExpressFee(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    status: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const stateList = ref([]);
  const logisticsList = ref([]);
  const goodsOptionList = ref([]);
  const export_field = ref({});
  const template_url = ref('');
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const selectedNum = ref(0);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",width: 50,
      // reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "Id",
      prop: "id"
    },
    {
      label: "国家",
      prop: "state",
    },
    {
      label: "商品属性",
      prop: "attributes"
    },
    {
      label: "物流名称",
      prop: "logistics"
    },

    {
      label: "重量段低位",
      prop: "weight_from"
    },
    {
      label: "重量段高位",
      prop: "weight_to"
    },
    {
      label: "公斤价",
      prop: "kilogram_price"
    },
    {
      label: "挂号费",
      prop: "reg_fee"
    },
    {
      label: "生效日期",
      prop: "time_start",
      minWidth: 120
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.status === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "创建用户",
      prop: "creator"
    },
    {
      label: "创建时间",
      prop: "created_at",width:120
    },
    {
      label: "更新时间",
      prop: "updated_at",width:120
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];
  // const buttonClass = computed(() => {
  //   return [
  //     "!h-[20px]",
  //     "reset-margin",
  //     "!text-gray-500",
  //     "dark:!text-white",
  //     "dark:hover:!text-primary"
  //   ];
  // });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${ row.name}</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(() => {
      // switchLoadMap.value[index] = Object.assign(
      //   {},
      //   switchLoadMap.value[index],
      //   {
      //     loading: true
      //   }
      // );
      row.swith = 1
      getExpressFeeList(row,"put").then(res=>{
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message(`已${row.status === 2 ? "停用" : "启用"}${row.name}-${row.state}物流价格`, {
          type: "success"
        });
      })
    })
      .catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function handleDelete(row) {
    getExpressFeeList(row,"delete").then(res=>chores(row,res,'删除'))
  }
  function handleBatchDelete(val) {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const params = {id:getKeyList(curSelected, "id")}
    getExpressFeeList(params,"delete").then(res=>chores(params,res,'删除'))
    tableRef.value.getTableRef().clearSelection();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    console.log(4444,val)
    // 重置表格高度
    tableRef.value.setAdaptive();
  }


  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const { data } = await getExpressFeeList(toRaw(form),'get');
    dataList.value = data.data;
    export_field.value = data.export_field;
    template_url.value = data.template_url;
    stateList.value = data.state;
    logisticsList.value = data.logistics;
    goodsOptionList.value = data.goods_option;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function chores(curData,res,title,done) {
    if(res.code===0){
      let messageText = `${title}成功`
      if('state' in curData){
        messageText = `您${title}了物流价格为${curData.state}的这条数据`
      }else if('id' in curData){
        messageText = `您${title}了${curData.id.length}条数据`
      }
      message(messageText, {
        type: "success"
      });
      if(done!=undefined)done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    }else{
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}物流价格`,
      props: {
        formInline: JSON.parse(JSON.stringify(row||{status:1})),
        stateList:stateList.value,
        logisticsList:logisticsList.value,
        goodsOptionList:goodsOptionList.value,
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              getExpressFeeList(curData,"post").then(res=>chores(curData,res,title,done))
            } else {
              curData.id = row.id
              // 实际开发先调用修改接口，再进行下面操作
              getExpressFeeList(curData,"put").then(res=>chores(curData,res,title,done))
            }
          }
        });
      }
    });
  }




  const exportExcel = async () => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const { data } = await getExpressFeeList(toRaw({page:1,export:1,limit:10000,'id':getKeyList(curSelected, "id").join(',')}),'get');
    // downloadByUrl(data.url)
    window.open(data.url, '_blank')
  };


  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }


  const onQueryChanged = (query: string) => {
      treeRef.value!.filter(query);
    };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
  });

  function onFormImportClick(row) {
    addDrawer({
      size: "70%",
      title: "导入物流价格信息",
      contentRenderer: () => forms,
      props: {
        formInline: {
          template_url: template_url,
          dataList:[[]],
          export_field:export_field,
          checkCond:[stateList.value,logisticsList.value,goodsOptionList.value]
        }
      },
      closeOnClickModal: false,
      sureBtnLoading: true,
      beforeSure: (done, { options, index,closeLoading }) => {
        const { formInline } = options.props as FormProps;
        if(formInline.dataList[0].length == 0){
          message(`你没有导入数据`);
        }else{
          importExpressFeeList({list:formInline.dataList},"post").then(res=>{
            if(res.code==0){
              if(res.data.filter(x=>x.i_status!='ok').length==0){//全部成功的关闭
                done();
                message(`已成功导入${res.data.filter(x=>x.i_status=='ok').length}条`, {
                  type: "success"
                });
              }else{
                formInline.dataList = formInline.dataList.map((da,idx) => ({
                  ...da,
                  '状态检查': res.data[idx]?.i_status||''
                }));
                message(`已成功导入${res.data.filter(x=>x.i_status=='ok').length}条,失败${res.data.filter(x=>x.i_status!='ok').length}条`, {
                  type: "warning"
                });
              }
              onSearch();
            }else{
              formInline.dataList = []
              message(`导入失败,失败原因：`+res.message, {
                type: "error"
              });
            }
            closeLoading();
          })
        }
        // done(); // 需要关闭把注释解开即可
      },
    });
  }

  return {
    form,
    onFormImportClick,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,selectedNum,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    stateList,logisticsList,goodsOptionList,handleBatchDelete,
    onSearch,
    resetForm,
    openDialog,
    exportExcel,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
